package com.example.weight.greenSeasons.waterDeal;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.SolidLiquid.ribaoyang7_5;
import com.example.weight.greenSeasons.SolidLiquid.shebeiyunxing7_1jiancharen;
import com.example.weight.greenSeasons.flocculation.xuningribaoyangChecker;
import com.example.weight.wormHandle.cultivate.SmallWormBreedingIncoming;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EquipmentRunningTableCheck extends AppCompatActivity {

    private TitleBar titleBar;
    String name;
    private RequestQueue queue;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    private Button saveButton;
    private TextView dateTextView;
    private TextView tvPressure1, tvPressure2, tvPressure3, tvFrequency1, tvFrequency2;
    private EditText etRemarks;
    private CheckBox cb1, cb2, cb3, cb4, cb5;
    private int cb1_state, cb2_state, cb3_state, cb4_state, cb5_state;
//    private String id1 = "-100", id2 = "-100", id3 = "-100", id4 = "-100", id5 = "-100";
    private String id, factory;
    private List<CheckBox> cbs;
//    private Integer pressure1, pressure2, pressure3, frequency1, frequency2, frequency3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equipment_running_table_check);

        titleBar=findViewById(R.id.titleBar);
        saveButton = findViewById(R.id.btnSave);
        dateTextView = findViewById(R.id.tvDate);
        tvPressure1 = findViewById(R.id.tvPressure1);
        tvPressure2 = findViewById(R.id.tvPressure2);
        tvPressure3 = findViewById(R.id.tvPressure3);
        tvFrequency1 = findViewById(R.id.tvFrequency1);
        tvFrequency2 = findViewById(R.id.tvFrequency2);

        cb1 = findViewById(R.id.cb1);
        cb2 = findViewById(R.id.cb2);
        cb3 = findViewById(R.id.cb3);
        cb4 = findViewById(R.id.cb4);
        cb5 = findViewById(R.id.cb5);
        cbs=new ArrayList<>();
        cbs.add(cb1);cbs.add(cb2);cbs.add(cb3);cbs.add(cb4);cbs.add(cb5);

//        cb1.setEnabled(false);
//        cb2.setEnabled(false);
//        cb3.setEnabled(false);
//        cb4.setEnabled(false);
//        cb5.setEnabled(false);
        cb1_state=cb2_state=cb3_state=cb4_state=cb5_state=0;

        etRemarks = findViewById(R.id.et_remarks);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        queue = Volley.newRequestQueue(this);

        dateTextView.setText(simpleDateFormat.format(new Date()));

        //注册勾选框处理事件
//        register();

        //获取当天填写的数据
        getInfo();

        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                if (!cb1.isChecked()) {
                    allDone(cb1.getText().toString());
                } else if (!cb2.isChecked()) {
                    allDone(cb2.getText().toString());
                } else if (!cb3.isChecked()) {
                    allDone(cb3.getText().toString());
                } else if (!cb4.isChecked()) {
                    allDone(cb4.getText().toString());
                } else if (!cb5.isChecked()) {
                    allDone(cb5.getText().toString());
                } else {
                    EquipmentRunningTableCheck.this.finish();
                }
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {

            }


        });

        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/SjqWaterProductionInspectionEquipment/getLast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject0 = new JSONObject(response);
                            Log.d("jy", response);
//                            JSONArray data;
//                            if (!jsonObject.get("data").toString().equals("null")) {
//                                data = jsonObject.getJSONArray("data");
//                                if (data.length() > 0) {
//                                    for (int i = 0; i < data.length(); i++) {
//                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
//                                        JSONObject record = data.getJSONObject(i);
//                                        Log.d("record", record.toString());
//                                        // 得到 每个对象中的属性值
//                                        if (record.get("equipmentName").equals(cb1.getText().toString())) {
//                                            Log.d("equipmentName", record.get("equipmentName").toString());
//                                            if (!record.get("inspector").toString().equals("null")) {
//                                                cb1.setChecked(true);
//                                                cb1.setEnabled(false);
//                                            }
//                                            id1 = record.get("id").toString();
//                                            if (record.get("isNormal").equals("正常")) {
//                                                TextView text = findViewById(R.id.equipment1_state);
//                                                text.setText("正常");
//                                                text.setTextColor(Color.parseColor("#018786"));
//                                            } else {
//                                                TextView text = findViewById(R.id.equipment1_state);
//                                                text.setText(record.get("remarks").toString());
//                                                text.setTextColor(Color.parseColor("#B00020"));
//                                            }
//                                        } else if (record.get("equipmentName").equals(cb2.getText().toString())) {
//                                            if (!record.get("inspector").toString().equals("null")) {
//                                                cb2.setChecked(true);
//                                                cb2.setEnabled(false);
//                                            }
//                                            id2 = record.get("id").toString();
//                                            if (record.get("isNormal").equals("正常")) {
//                                                TextView text = findViewById(R.id.equipment2_state);
//                                                text.setText("正常");
//                                                text.setTextColor(Color.parseColor("#018786"));
//                                            } else {
//                                                TextView text = findViewById(R.id.equipment2_state);
//                                                text.setText(record.get("remarks").toString());
//                                                text.setTextColor(Color.parseColor("#B00020"));
//                                            }
//                                        } else if (record.get("equipmentName").equals(cb3.getText().toString())) {
//                                            if (!record.get("inspector").toString().equals("null")) {
//                                                cb3.setChecked(true);
//                                                cb3.setEnabled(false);
//                                            }
//                                            id3 = record.get("id").toString();
//                                            if (record.get("isNormal").equals("正常")) {
//                                                TextView text = findViewById(R.id.equipment3_state);
//                                                text.setText("正常");
//                                                text.setTextColor(Color.parseColor("#018786"));
//                                            } else {
//                                                TextView text = findViewById(R.id.equipment3_state);
//                                                text.setText(record.get("remarks").toString());
//                                                text.setTextColor(Color.parseColor("#B00020"));
//                                            }
//                                        } else if (record.get("equipmentName").equals(cb4.getText().toString())) {
//                                            if (!record.get("inspector").toString().equals("null")) {
//                                                cb4.setChecked(true);
//                                                cb4.setEnabled(false);
//                                            }
//                                            id4 = record.get("id").toString();
//                                            if (record.get("isNormal").equals("正常")) {
//                                                TextView text = findViewById(R.id.equipment4_state);
//                                                text.setText("正常");
//                                                text.setTextColor(Color.parseColor("#018786"));
//                                            } else {
//                                                TextView text = findViewById(R.id.equipment4_state);
//                                                text.setText(record.get("remarks").toString());
//                                                text.setTextColor(Color.parseColor("#B00020"));
//                                            }
//                                        } else if (record.get("equipmentName").equals(cb5.getText().toString())) {
//                                            if (!record.get("inspector").toString().equals("null")) {
//                                                cb5.setChecked(true);
//                                                cb5.setEnabled(false);
//                                            }
//                                            id5 = record.get("id").toString();
//                                            if (record.get("isNormal").equals("正常")) {
//                                                TextView text = findViewById(R.id.equipment5_state);
//                                                text.setText("正常");
//                                                text.setTextColor(Color.parseColor("#018786"));
//                                            } else {
//                                                TextView text = findViewById(R.id.equipment5_state);
//                                                text.setText(record.get("remarks").toString());
//                                                text.setTextColor(Color.parseColor("#B00020"));
//                                            }
//                                        }
//                                    }
//                                }
//                            }
                            if (!jsonObject0.isNull("data")) {
                                JSONObject jsonObject=jsonObject0.getJSONObject("data");
                                    if("是".equals(jsonObject.get("pumpPressure1IsExam").toString())){
                                        cb1.setEnabled(false);
                                        cb1.setChecked(true);
                                    }
                                    if("是".equals(jsonObject.get("pumpPressure2IsExam").toString())){
                                        cb2.setEnabled(false);
                                        cb2.setChecked(true);
                                    }
                                    if("是".equals(jsonObject.get("pumpPressure3IsExam").toString())){
                                        cb3.setEnabled(false);
                                        cb3.setChecked(true);
                                    }
                                    if("是".equals(jsonObject.get("fanFrequency1IsExam").toString())){
                                        cb4.setEnabled(false);
                                        cb4.setChecked(true);
                                    }
                                    if("是".equals(jsonObject.get("fanFrequency2IsExam").toString())){
                                        cb5.setEnabled(false);
                                        cb5.setChecked(true);
                                    }
                            }
//                            cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                @Override
//                                public void onCheckedChanged(CompoundButton buttonView,
//                                                             boolean isChecked) {
//                                    // TODO Auto-generated method stub
//                                    if (isChecked) {
//                                        checkEquipment(cb1, id1);
//                                    }
//                                }
//                            });
//                            cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                @Override
//                                public void onCheckedChanged(CompoundButton buttonView,
//                                                             boolean isChecked) {
//                                    // TODO Auto-generated method stub
//                                    if (isChecked) {
//                                        checkEquipment(cb2, id2);
//                                    }
//                                }
//
//                            });
//                            cb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                @Override
//                                public void onCheckedChanged(CompoundButton buttonView,
//                                                             boolean isChecked) {
//                                    // TODO Auto-generated method stub
//                                    if (isChecked) {
//                                        checkEquipment(cb3, id3);
//                                    }
//                                }
//
//                            });
//                            cb4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                @Override
//                                public void onCheckedChanged(CompoundButton buttonView,
//                                                             boolean isChecked) {
//                                    // TODO Auto-generated method stub
//                                    if (isChecked) {
//                                        checkEquipment(cb4, id4);
//                                    }
//                                }
//
//                            });
//                            cb5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                                @Override
//                                public void onCheckedChanged(CompoundButton buttonView,
//                                                             boolean isChecked) {
//                                    // TODO Auto-generated method stub
//                                    if (isChecked) {
//                                        checkEquipment(cb5, id5);
//                                    }
//                                }
//                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(EquipmentRunningTableCheck.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        cb1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                boolean isChecked = cb1.isChecked();
                if(isChecked) {
                    checkEquipment(cb1,id,"cb1");
                }
            }

        });
        cb2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                boolean isChecked = cb2.isChecked();
                if(isChecked) {
                    checkEquipment(cb2,id,"cb2");
                }
            }

        });
        cb3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                boolean isChecked = cb3.isChecked();
                if(isChecked) {
                    checkEquipment(cb3,id,"cb3");
                }
            }

        });
        cb4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                boolean isChecked = cb4.isChecked();
                if(isChecked) {
                    checkEquipment(cb4,id,"cb4");
                }
            }

        });
        cb5.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                boolean isChecked = cb5.isChecked();
                if(isChecked) {
                    checkEquipment(cb5,id,"cb5");
                }
            }

        });
    }

    public void getInfo(){
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/SjqWaterProductionEquipmentRunning/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
//                            JSONArray datas = jsonObject.getJSONArray("data");
                            if (!jsonObject.isNull("data")) {
//                                for(int i=0;i<datas.length();i++){
                                    JSONObject data = jsonObject.getJSONObject("data");
                                id=data.get("id").toString();
                                tvPressure1.setText(data.getString("pumpPressure1"));
                                tvPressure2.setText(data.getString("pumpPressure2"));
                                tvPressure3.setText(data.getString("pumpPressure3"));
                                tvFrequency1.setText(data.getString("fanFrequency1"));
                                tvFrequency2.setText(data.getString("fanFrequency2"));
                                //                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(EquipmentRunningTableCheck.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

//    public void save(View view) {
////        if(etRemarks.getText().toString().equals("")) {
////            Toast.makeText(this, "请填写备注", Toast.LENGTH_SHORT).show();
////            return;
////        }
//
//        new AlertDialog.Builder(this)
//                .setTitle("确定保存吗？")
//                .setCancelable(false)
//                .setNegativeButton("取消", ((dialog, which) ->
//                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
//                .setPositiveButton("确定", (dialog, which) -> {
//                    //提交请求
//                    RequestQueue queue = Volley.newRequestQueue(this);
//                    String url = Config.url + "/sjq/SjqWaterProductionEquipmentRunning/addRemarks";
//                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
//                            new Response.Listener<String>() {
//                                @Override
//                                public void onResponse(String response) {
//                                    try {
//                                        JSONObject jsonObject = new JSONObject(response);
//                                        String code = jsonObject.getString("code");
//                                        if (code.startsWith("2")){
//                                            Toast.makeText(EquipmentRunningTableCheck.this,
//                                                    "保存成功", Toast.LENGTH_SHORT).show();
//                                        }
//                                        else
//                                            Toast.makeText(EquipmentRunningTableCheck.this,
//                                                    "保存失败", Toast.LENGTH_SHORT).show();
//                                    } catch (JSONException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }, new Response.ErrorListener() {
//                        @Override
//                        public void onErrorResponse(VolleyError error) {
//                            Toast.makeText(EquipmentRunningTableCheck.this, "保存失败", Toast.LENGTH_SHORT).show();
//                        }
//                    }) {
//                        @Override
//                        protected Map<String, String> getParams() throws AuthFailureError {
//                            Map<String, String> map=new HashMap<>();
//                            map.put("remarks", etRemarks.getText().toString());
//                            map.put("examiner", name);
//                            return map;
//                        }
//                    };
//                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//                    queue.add(stringRequest);
//                })
//                .show();
//    }

    public void allDone(String equipment_name){
        new AlertDialog.Builder(this)
                .setTitle(" “"+ equipment_name +"” 未检查，是否退出")
                .setCancelable(false)
                .setNegativeButton("否", ((dialog, which) -> {
                }))
                .setPositiveButton("是", (dialog, which) ->{
                    EquipmentRunningTableCheck.this.finish();
                })
                .show();
    }

    public void checkEquipment(CheckBox cb, String id,String ename) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                //.setTitle(" “"+ equipment_name.getText().toString() +"” 已检查")
                .setTitle("操作人结论是否正确？如果有误请在下方填写问题")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    cb.setChecked(false);
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/SjqWaterProductionEquipmentRunning/addRemarks";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            Toast.makeText(EquipmentRunningTableCheck.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            cb.setEnabled(false);
                                        }
                                        else
                                            Toast.makeText(EquipmentRunningTableCheck.this,
                                                    "1保存失败", Toast.LENGTH_SHORT).show();

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(EquipmentRunningTableCheck.this,
                                    "2保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", id);   ///------------------------这里要id
                            if(ename.equals("cb1")){
                                map.put("pump_pressure_1_remark", equipment_problem.getText().toString());
                            }
                            if(ename.equals("cb2")){
                                map.put("pump_pressure_2_remark", equipment_problem.getText().toString());
                            }
                            if(ename.equals("cb3")){
                                map.put("pump_pressure_3_remark", equipment_problem.getText().toString());
                            }
                            if(ename.equals("cb4")){
                                map.put("fan_frequency_1_remark", equipment_problem.getText().toString());
                            }
                            if(ename.equals("cb5")){
                                map.put("fan_frequency_2_remark", equipment_problem.getText().toString());
                            }
                            map.put("examiner", name);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}